//
//  RecommendViewController.m
//  project_delicious
//
//  Created by 章历杰 on 15/3/21.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "RecommendViewController.h"
#import "RecommCell.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "RoundsOfRecomend.h"
#import "Details.h"
#import "UIColor+AddColor.h"
#import "LatestViewController.h"
#import "MJRefresh.h"

#import "LatDetailsViewController.h"
#import "D_TimeViewController.h"

#import "MBProgressHUD.h"

#import "SphereMenu.h"
@interface RecommendViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, SphereMenuDelegate, UIAlertViewDelegate>

@property (nonatomic, retain) UIScrollView *recommendSV;
@property (nonatomic, retain) NSMutableDictionary *mDic;
@property (nonatomic, retain) NSMutableArray *recommendArr;
//最新的scrollView
@property (nonatomic, retain) UIScrollView *latScroV;

//栏目
@property (nonatomic, retain) NSMutableArray *type;

//推荐tableView
@property (nonatomic, retain) UITableView *tableView;


@property (nonatomic, retain) MBProgressHUD *HUD;
@end

@implementation RecommendViewController
- (void)dealloc
{
    [_recommendSV release];
    [_mDic release];
    [_recommendArr release];
    [_latScroV release];
    [_type release];
    [_tableView release];
    
    [_HUD release];
    
    [super dealloc];
}
//解析数据方法
- (void)startAnalyze:(NSString *)str
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"成功");
        //接收data
        self.mDic = [responseObject objectForKey:@"data"];
        //推荐列接收data的推荐数组
        NSMutableArray *array = [self.mDic objectForKey:@"app_index_recommand"];
        //NSLog(@"%@", array);
        //NSLog(@"%ld", array.count);
        self.recommendArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in array) {
            Details *details = [[Details alloc] initWithDictionary:dic];
            [self.recommendArr addObject:details];
            [details release];
        }
        
        
        //整个页面都是一个scrollView
        self.recommendSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        self.recommendSV.delegate = self;
        
        //TopPicture
        UIImageView *topPic = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
        topPic.image = [UIImage imageNamed:@"QQ20150406-11.png"];
        topPic.backgroundColor = [UIColor redColor];
        [self.recommendSV addSubview:topPic];
        [topPic release];
    
        //栏目
        UILabel *prog = [[UILabel alloc] initWithFrame:CGRectMake(15, 50, self.view.frame.size.width-15, 15)];
        prog.text = @"逛逛";
        //latest.backgroundColor = [UIColor blueColor];
        prog.font = [UIFont systemFontOfSize:14];
        prog.backgroundColor = [UIColor colorFromHexCode:@"#d1c7b7"];
        [self.recommendSV addSubview:prog];
        [prog release];
        UIImageView *progDiv = [[UIImageView alloc] initWithFrame:CGRectMake(0, prog.frame.origin.y, 15, 15)];
        progDiv.image = [UIImage imageNamed:@"divide.png"];
        progDiv.backgroundColor = [UIColor colorFromHexCode:@"#d1c7b7"];
        [self.recommendSV addSubview:progDiv];
        [progDiv release];
        
        // 获取当地时间
        NSDate *localDate = [NSDate dateWithTimeIntervalSinceNow:28800];
        NSString *string = [NSString stringWithFormat:@"%@", localDate];
        NSRange range = NSMakeRange(11, 8);
        NSString *str = [string substringWithRange:range];
        NSRange range1 = NSMakeRange(0, 2);
        NSString *hour = [str substringWithRange:range1];
        NSInteger a = [hour integerValue];
        if ((a > 0)&&(a < 18)) {
            //云1
            UIImageView *cloud1 = [[UIImageView alloc] initWithFrame:CGRectMake(5, 50, 70, 50)];
            //cloud1.backgroundColor = [UIColor redColor];
            cloud1.image = [UIImage imageNamed:@"cloud1.png"];
            cloud1.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud1];
            [cloud1 release];
            //云2
            UIImageView *cloud4 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 100, 100, 70)];
            cloud4.image = [UIImage imageNamed:@"cloud4.png"];
            cloud4.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud4];
            [cloud4 release];
            //云3
            UIImageView *cloud2 = [[UIImageView alloc] initWithFrame:CGRectMake(self.recommendSV.frame.size.width-120, 70, 120, 80)];
            //cloud2.backgroundColor = [UIColor redColor];
            cloud2.image = [UIImage imageNamed:@"cloud2.png"];
            cloud2.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud2];
            //云4
            UIImageView *cloud3 = [[UIImageView alloc] initWithFrame:CGRectMake(self.recommendSV.frame.size.width-150, 145, 90, 60)];
            //cloud2.backgroundColor = [UIColor redColor];
            cloud3.image = [UIImage imageNamed:@"cloud3.png"];
            cloud3.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud3];
            [cloud3 release];

            //白天
            UIImage *startImage = [UIImage imageNamed:@"sun.png"];
            UIImage *time = [UIImage imageNamed:@"Dtime.png"];
            UIImage *map = [UIImage imageNamed:@"Dmap.png"];
            UIImage *afternoon = [UIImage imageNamed:@"Dafternoon.png"];
            UIImage *health = [UIImage imageNamed:@"Dhealth.png"];
            NSArray *images = @[time, map, afternoon, health];
            SphereMenu *sp = [[SphereMenu alloc] initWithStartPoint:CGPointMake(130, 120) startImage:startImage submenuImages:images];
            sp.delegate = self;
            [self.recommendSV addSubview:sp];
            
            
            
            
        } else {
            //云1
            UIImageView *cloud1 = [[UIImageView alloc] initWithFrame:CGRectMake(100, 80, 70, 50)];
            //cloud1.backgroundColor = [UIColor redColor];
            cloud1.image = [UIImage imageNamed:@"cloud1.png"];
            cloud1.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud1];
            [cloud1 release];
            //云2
            UIImageView *cloud2 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 120, 80)];
            //cloud2.backgroundColor = [UIColor redColor];
            cloud2.image = [UIImage imageNamed:@"cloud2.png"];
            cloud2.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud2];
            [cloud2 release];
            //云4
            UIImageView *cloud4 = [[UIImageView alloc] initWithFrame:CGRectMake(100, 145, 90, 60)];
            //cloud2.backgroundColor = [UIColor redColor];
            cloud4.image = [UIImage imageNamed:@"cloud3.png"];
            cloud4.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud4];
            [cloud4 release];
            //晚上
            UIImage *startImage = [UIImage imageNamed:@"moon.png"];
            UIImage *time = [UIImage imageNamed:@"Dtime.png"];
            UIImage *map = [UIImage imageNamed:@"Dmap.png"];
            UIImage *afternoon = [UIImage imageNamed:@"Dafternoon.png"];
            UIImage *health = [UIImage imageNamed:@"Dhealth.png"];
            NSArray *images = @[time, map, afternoon, health];
            SphereMenu *sp = [[SphereMenu alloc] initWithStartPoint:CGPointMake(200, 120) startImage:startImage submenuImages:images];
            sp.delegate = self;
            [self.recommendSV addSubview:sp];
            
            //云3
            UIImageView *cloud3 = [[UIImageView alloc] initWithFrame:CGRectMake(self.recommendSV.frame.size.width-100, 110, 90, 60)];
            //cloud2.backgroundColor = [UIColor redColor];
            cloud3.image = [UIImage imageNamed:@"cloud4.png"];
            cloud3.layer.masksToBounds = YES;
            [self.recommendSV addSubview:cloud3];
            [cloud3 release];
        }
        
        //最新
        UILabel *latest = [[UILabel alloc] initWithFrame:CGRectMake(15, 185, self.view.frame.size.width-15, 15)];
        latest.text = @"最新";
        //latest.backgroundColor = [UIColor blueColor];
        latest.font = [UIFont systemFontOfSize:14];
        latest.backgroundColor = [UIColor colorFromHexCode:@"#d1c7b7"];
        [self.recommendSV addSubview:latest];
        [latest release];
        UIImageView *latestDiv = [[UIImageView alloc] initWithFrame:CGRectMake(0, latest.frame.origin.y, 15, 15)];
        latestDiv.image = [UIImage imageNamed:@"divide.png"];
        latestDiv.backgroundColor = [UIColor colorFromHexCode:@"#d1c7b7"];
        [self.recommendSV addSubview:latestDiv];
        [latestDiv release];
        //最新的图片(scrollView)
        
        self.latScroV = [[UIScrollView alloc] initWithFrame:CGRectMake(5, latest.frame.origin.y+latest.frame.size.height, self.recommendSV.frame.size.width-10, 100)];
        self.latScroV.backgroundColor = [UIColor clearColor];
        //建立数组接收data的"最新"数组
        NSMutableArray *latestImages = [self.mDic objectForKey:@"index_index_latest"];
        //NSLog(@"%ld", latestImages.count);
        //for循环添加图片
        for (NSInteger i = 0; i < latestImages.count; i++) {
            UIImageView *smallIV = [[UIImageView alloc] initWithFrame:CGRectMake(100*i+10, 5, 90, 90)];
            NSString *str =[latestImages[i] objectForKey:@"main_photo_url"];
            str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:str];
            [smallIV setImageWithURL:url];
            smallIV.layer.cornerRadius = 45;
            smallIV.layer.masksToBounds = YES;
            [self.latScroV addSubview:smallIV];
            [smallIV release];
        }
        self.latScroV.contentSize = CGSizeMake(1000, 0);
        //滚动条
        self.latScroV.showsHorizontalScrollIndicator = NO;
        
        [self.recommendSV addSubview:self.latScroV];
        [self.latScroV release];
        //给最新图片添加点击方法
        UITapGestureRecognizer *latestTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(latestTapAction)];
        [self.latScroV addGestureRecognizer:latestTap];
        [latestTap release];

        
        
        //推荐(tableView)
        //self.latScroV.frame.origin.y+self.latScroV.frame.size.height+10
        
        UILabel *recommand = [[UILabel alloc] initWithFrame:CGRectMake(15, self.latScroV.frame.origin.y+self.latScroV.frame.size.height+5, self.view.frame.size.width-15, 15)];
        recommand.text = @"推荐";
        recommand.font = [UIFont systemFontOfSize:14];
        recommand.backgroundColor = [UIColor colorFromHexCode:@"#d1c7b7"];
        [self.recommendSV addSubview:recommand];
        [recommand release];
        UIImageView *recommendDiv = [[UIImageView alloc] initWithFrame:CGRectMake(0, recommand.frame.origin.y, 15, 15)];
        recommendDiv.image = [UIImage imageNamed:@"divide.png"];
        recommendDiv.backgroundColor = [UIColor colorFromHexCode:@"#d1c7b7"];
        [self.recommendSV addSubview:recommendDiv];
        [recommendDiv release];
        //推荐列
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.recommendSV.frame.origin.x+10, recommand.frame.origin.y+17, self.recommendSV.frame.size.width-20, 300*self.recommendArr.count) style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.backgroundColor = [UIColor clearColor];
        self.tableView.separatorColor = [UIColor clearColor];
        
        [self.tableView registerClass:[RecommCell class] forCellReuseIdentifier:@"reuse"];
        self.tableView.scrollEnabled = NO;
        
        [self.recommendSV addSubview:self.tableView];
        [self.tableView release];
        
        self.recommendSV.contentSize = CGSizeMake(self.view.frame.size.width,self.tableView.frame.origin.y+self.tableView.frame.size.height+50);
        [self.view addSubview:self.recommendSV];
        [_recommendSV release];
        
        //下拉刷新
        [self.recommendSV addHeaderWithTarget:self action:@selector(headerRe)];
        
        //上拉加载
        //[self.recommendSV addFooterWithTarget:self action:@selector(footerRefresh)];
        
        //等待加载
        [_HUD hide:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"错误信息%@",error);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    }];
    //栏目的数据POST请求
    NSString *lanmu = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_topic_index&parameters=%7B%22_end%22%3A%2210%22%2C%22_start%22%3A%220%22%7D";
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    [manager2 POST:lanmu parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.type = [NSMutableArray array];
        self.type = [[responseObject objectForKey:@"data"] objectForKey:@"topic_type"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"错误");
    }];
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor cyanColor];
//    [self checkNetworkStatus];
    //隐藏navigation
    self.navigationController.navigationBarHidden = YES;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"IMG_1345.JPG"]];
    
    //AFNetWorking来请求POST数据
    NSString *str = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_index_recommand_new&parameters=%7B%22_end%22%3A%2215%22%2C%22_member_id%22%3A%220%22%2C%22_start%22%3A%220%22%7D";

    
    
    self.HUD = self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    _HUD.labelText = @"Loading";
    //_HUD.color = [UIColor clearColor];
    _HUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_HUD];
    [_HUD release];
    [_HUD show:YES];
    
    [self startAnalyze:str];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *str = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_index_recommand_new&parameters=%7B%22_end%22%3A%2215%22%2C%22_member_id%22%3A%220%22%2C%22_start%22%3A%220%22%7D";
    [self startAnalyze:str];

}
//四个栏目
- (void)sphereDidSelected:(int)index
{
    if (index == 0) {
        [self timeTapAction];
    } else if (index == 1) {
        [self mapTapAction];
    } else if (index == 2) {
        [self afternoonTapAction];
    } else if (index == 3) {
        [self healthTapAction];
    } else {
        NSLog(@"%d", index);
    }
}

//下拉刷新
- (void)headerRe
{
    NSString *str = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_index_recommand_new&parameters=%7B%22_end%22%3A%2215%22%2C%22_member_id%22%3A%220%22%2C%22_start%22%3A%220%22%7D";
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.mDic = [responseObject objectForKey:@"data"];
        NSMutableArray *array = [self.mDic objectForKey:@"app_index_recommand"];
        //self.recommendArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in array) {
            Details *details = [[Details alloc] initWithDictionary:dic];
            [self.recommendArr addObject:details];
            [details release];
        }
        //栏目的数据POST请求
        {
        NSString *lanmu = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_topic_index&parameters=%7B%22_end%22%3A%2210%22%2C%22_start%22%3A%220%22%7D";
        AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
        [manager2 POST:lanmu parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            self.type = [NSMutableArray array];
            self.type = [[responseObject objectForKey:@"data"] objectForKey:@"topic_type"];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"错误");
        }];
        }
        
        [self.recommendSV headerEndRefreshing];
        
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"错误信息%@",error);
    }];
    
}
//上拉加载
/*
- (void)footerRefresh
{
    NSString *str1 = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_index_recommand_new&parameters=%7B%22_end%22%3A%2215%22%2C%22_member_id%22%3A%2215%22%2C%22_start%22%3A%22";
    static NSInteger a = 0;
    a = a + 10;
    NSString *str2 = [NSString stringWithFormat:@"%ld", (long)a];
    NSString *str3 = @"%22%7D";
    NSString *str = [NSString stringWithFormat:@"%@%@%@", str1, str2, str3];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.mDic = [responseObject objectForKey:@"data"];
        NSMutableArray *array = [self.mDic objectForKey:@"app_index_recommand"];
//        self.recommendArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in array) {
            Details *details = [[Details alloc] initWithDictionary:dic];
            [self.recommendArr addObject:details];
            [details release];
        }
        
        [self.recommendSV footerEndRefreshing];
        
        [self.tableView reloadData];
         //(latest.frame.origin.y+latest.frame.size.height)+(_latScroV.frame.size.height+_latScroV.frame.origin.y)+(programa.frame.origin.y+programa.frame.size.height)+(time.frame.size.height+time.frame.origin.y)+(map.frame.origin.y+map.frame.size.height)+(afternoon.frame.size.height+afternoon.frame.origin.y)+(health.frame.origin.y+health.frame.size.height)+(recommand.frame.size.height+recommand.frame.origin.y)+self.tableView.frame.origin.y+self.tableView.frame.size.height)
        
        self.recommendSV.contentSize = CGSizeMake(self.view.frame.size.width, self.tableView.frame.origin.y+self.tableView.frame.size.height);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"错误信息%@",error);
    }];
  
}
*/

//最新ScrollView---->点击跳转
- (void)latestTapAction
{
    
    LatestViewController *lat = [[LatestViewController alloc] init];
    lat.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lat animated:NO];
    [lat release];
    
}
//美食美刻
- (void)timeTapAction
{
    
    D_TimeViewController *time = [[D_TimeViewController alloc] init];
    time.num = [self.type[0] objectForKey:@"topic_type_id"];
    time.name = [self.type[0] objectForKey:@"type_name"];
    time.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:time animated:NO];
    [time release];
}
//吃货地图
- (void)mapTapAction
{
    D_TimeViewController *time = [[D_TimeViewController alloc] init];
    time.num = [self.type[1] objectForKey:@"topic_type_id"];
    time.name = [self.type[1] objectForKey:@"type_name"];
    time.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:time animated:NO];
    [time release];
}
//午后时光
- (void)afternoonTapAction
{
    D_TimeViewController *time = [[D_TimeViewController alloc] init];
    time.num = [self.type[2] objectForKey:@"topic_type_id"];
    time.name = [self.type[2] objectForKey:@"type_name"];
    time.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:time animated:NO];
    [time release];
}
//因为健康
- (void)healthTapAction
{
    D_TimeViewController *time = [[D_TimeViewController alloc] init];
    time.num = [self.type[3] objectForKey:@"topic_type_id"];
    time.name = [self.type[3] objectForKey:@"type_name"];
    time.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:time animated:NO];
    [time release];
}
//推荐cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.recommendArr.count;
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}
//cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *str = @"reuse";
    RecommCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
//    if (cell == nil) {
//        cell = [[[RecommCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
//    }
    cell.backgroundColor = [UIColor clearColor];
    cell.details = [self.recommendArr objectAtIndex:indexPath.item];
    
    return cell;
    
}
//选中cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LatDetailsViewController *lat = [[LatDetailsViewController alloc] init];
    lat.num = [[self.recommendArr objectAtIndex:indexPath.item] member_share_id];
    lat.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lat animated:NO];
    //lat.hidesBottomBarWhenPushed = NO;
    [lat release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
